package file;
import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-08-07
 * Time: 16:31
 */
//写一个程序, 将一个文件复制到目标路径
public class Demo13 {
    public static void main(String[] args) {
        //准备工作
        System.out.println( " 请输入要复制的文件路径 :   ");
        Scanner scanner = new Scanner(System.in);
        String srcPath = scanner.next();
        File srcfile = new File(srcPath);

        if( !srcfile.exists()) {
            System.out.println("要复制的文件不存在");
            return;
        }

        if( !srcfile.isFile()) {
            System.out.println("要复制的文件不是普通文件");
            return;
        }

        System.out.println("请输入要复制的目标路径 : ");
        String destPath = scanner.next();
        File destfile = new File(destPath);
        if ( destfile.exists()) {
            System.out.println("要复制的目标已经存在!");
            return;
        }

        /**
         * 进行拷贝工作
         */
        try(InputStream inputStream = new FileInputStream(srcPath)) {
            try(OutputStream outputStream = new FileOutputStream(destPath)) {
                //buf 作为缓冲区 ,先将读到的内容,放入buf中,再写到目标文件中
                byte[] buf = new byte[1024];
                while( true) {
                    int len = inputStream.read(buf);
                    if( len == -1) {
                        //文件读完了
                        break;
                    }
                    //写到目标文件中
                    outputStream.write(buf,0,len);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("复制完成!");
    }
}
